package com.lcache.core.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.lcache.common.config.ConfigReader;
import com.lcache.common.mq.RocketMQSender;
import com.lcache.core.service.Level1Cache;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.apis.ClientException;

import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;

/**
 * @program: lcache
 * @description: caffeine缓存
 * @author: Alex Wu
 * @createDate: 2025-04-21 17:10
 **/

@Slf4j
public class CaffeineCache implements Level1Cache {

    private final Cache<String, Object> caffeine;

    public CaffeineCache() {
        this.caffeine = Caffeine.newBuilder()
                .expireAfterWrite(10, TimeUnit.MINUTES)
                .maximumSize(10000)
                .build();
    }

    @Override
    public Object get(String key) {
        return caffeine.getIfPresent(key);
    }

    @Override
    public void set(String key, Object value) {
        caffeine.put(key, value);
        // 异步通知所有服务器更新1级缓存
        try {
            RocketMQSender sender = RocketMQSender.getInstance(
                    ConfigReader.getInstance().getOrDefault("rocketmq.endpoint", String.class, ""),
                    ConfigReader.getInstance().getOrDefault("rocketmq.cache-consumer-topic", String.class, "")
            );

            String msg = key + ":" + value.toString();
            log.info("MQ 转发的信息{}", msg);
            sender.send("l1cache", key, msg);
            log.info("消息已通过 MQ 转发{}", msg);
        } catch (ClientException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateFromMQ(String key, Object value) {
        // 更新本地缓存
        if (value == null) {
            caffeine.invalidate(key);
        } else {
            caffeine.put(key, value);
        }
    }

    @Override
    public void delete(String key) {
        caffeine.invalidate(key);
    }
}

